package com.example.mynetwork2.mvpdesign.model;

import com.example.mynetwork2.mvpdesign.bean.Fanyi;
import com.example.mynetwork2.mvpdesign.presenter.ICidianPresenter;
import com.example.mynetwork2.mvpdesign.view.iview.IFanyiView;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class FanyiModel implements IfanyiModel {
    OkHttpClient  okHttpClient  = new OkHttpClient();
    Fanyi fanyi = new Fanyi();
    @Override
    public void handleData(String input, ICidianPresenter iCidianPresenter) {

        Request request = new Request.Builder()
                .url("http://fanyi.youdao.com/openapi.do?keyfrom=Yanzhikai&key=2032414398&type=data&doctype=json&version=1.1&q=" + input)
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                //失败时
                iCidianPresenter.onError();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String json = response.body().string();
                // 用Gson方式解析获得的json字符串
                Gson gson = new Gson();
                fanyi = gson.fromJson(json.trim(),fanyi.getClass());
                // 回调监听器的函数把处理数据后的结果（翻译结果）返回给Presenter层
                iCidianPresenter.onSuccess(fanyiToString(fanyi));
            }
        });

    }

    //转成能在TextView显示的内容
    @Override
    public String fanyiToString(Fanyi fy) {
        // 处理解析后的json数据，转成UI输出的字符串
        String strexplain = "解释：";
        String strphonetic = "发音：";
        String strweb = "网络释义：";
        if (fy.getBasic() == null){return "你所查找的还没有准确翻译";}
        for (int i = 0; i<fy.getBasic().getExplains().size(); i++){
            strexplain +=fy.getBasic().getExplains().get(i)+"\n";
            if (i != fy.getBasic().getExplains().size()-1 )
            {strexplain +="\t\t\t\t";}
        }
        strphonetic += fy.getBasic().getPhonetic()+"\n";
        for (int i = 0; i<fy.getWeb().size(); i++){
            for(int j = 0; j<fy.getWeb().get(i).getValue().size();j++)
            {
                strweb += fy.getWeb().get(i).getValue().get(j)+",";
            }
            strweb += fy.getWeb().get(i).getKey()+"\n";
            strweb += "\t\t\t\t\t\t\t";
        }
        return strexplain+"\n"+strphonetic+"\n"+strweb;
    }
}
